package com.aidex.wxCompany;


import com.aidex.framework.cache.ConfigUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Component
public class WxWorkService {


    private String accessToken;
    private long expiresTime;

    public static void main(String[] args) {
        String agentId = "1000013";
        // 构造消息体
        String corpId = "wwef2529d371419b3a";
        String corpSecret = "4BYelkhf-gFOz5X_pfZqlYzwj9vBPSuEKSORt5oqGLA";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpSecret}";
        Map<String, Object> res = new RestTemplate().getForObject(url, Map.class, corpId, corpSecret);
        String accessToken = (String) res.get("access_token");
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token={token}";
        // 构造消息体
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", "17771704470"); // 接收用户ID（多个用|分隔）
        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(url, params, Map.class, accessToken);
        String userId = "";
        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                userId = null;
            } else {
                userId = (String) body.get("userid");
            }
        } else {
            userId = null;
        }


        Map<String, Object> message = new HashMap<>();
        message.put("touser", userId); // 接收用户ID（多个用|分隔）
        message.put("toparty", "");//部门ID
        message.put("totag", ""); //tag
        message.put("msgtype", "text");
        message.put("agentid", agentId);
        Map<String, String> text = new HashMap<>();
        text.put("content", "新客户来了\n123");
        message.put("text", text);
        // 发送POST请求
        restTemplate = new RestTemplate();
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}";
        response = restTemplate.postForEntity(url, message, Map.class, accessToken);
        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                throw new RuntimeException("发送失败: " + body.get("errmsg"));
            }
        } else {
            throw new RuntimeException("请求失败: " + response.getStatusCode());
        }
    }

    // 获取AccessToken（带缓存）
    public String getAccessToken() {
        if (accessToken == null || System.currentTimeMillis() > expiresTime) {
            String corpId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.corpId").getConfigValue();
            String corpSecret = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.corpSecret").getConfigValue();
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpSecret}";
            Map<String, Object> response = new RestTemplate().getForObject(url, Map.class, corpId, corpSecret);
            accessToken = (String) response.get("access_token");
            expiresTime = System.currentTimeMillis() + ((Integer) response.get("expires_in") - 300) * 1000L;
        }
        return accessToken;
    }

    public void sendTextMessage(String userId, String content) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}";
        String agentId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.agentId").getConfigValue();
        // 构造消息体
        Map<String, Object> message = new HashMap<>();
        message.put("touser", userId); // 接收用户ID（多个用|分隔）
        message.put("toparty", "");//部门ID
        message.put("totag", ""); //tag
        message.put("msgtype", "text");
        message.put("agentid", agentId);
        Map<String, String> text = new HashMap<>();
        text.put("content", content);
        message.put("text", text);

        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(url, message, Map.class, getAccessToken());

        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                throw new RuntimeException("发送失败: " + body.get("errmsg"));
            }
        } else {
            throw new RuntimeException("请求失败: " + response.getStatusCode());
        }
    }

    public void sendMarkdownMessage(String userId, String content) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}";
        String agentId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.agentId").getConfigValue();
        Map<String, Object> message = new HashMap<>();
        message.put("touser", userId);
        message.put("msgtype", "markdown");
        message.put("agentid", agentId);

        Map<String, String> markdownContent = new HashMap<>();
        markdownContent.put("content",
                "### 系统通知\n" + "> **时间**: " + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "\n" +
                        "\n" + "> **内容**: \n" + content + "\n\n" + "[点击查看详情](https://your-domain.com)");
        message.put("markdown", markdownContent);

        sendToWxWork(url, message);
    }

    public void sendNewsMessage(String userId, String title, String description, String url, String picUrl) {
        String apiUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}";
        String agentId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.agentId").getConfigValue();
        Map<String, Object> message = new HashMap<>();
        message.put("touser", userId);
        message.put("msgtype", "news");
        message.put("agentid", agentId);

        // 构建图文消息结构
        Map<String, Object> article = new HashMap<>();
        article.put("title", title);
        article.put("description", description);
        article.put("url", url);
        article.put("picurl", picUrl);

        Map<String, Object> newsContent = new HashMap<>();
        newsContent.put("articles", Collections.singletonList(article));
        message.put("news", newsContent);

        sendToWxWork(apiUrl, message);
    }

    //公共发送方法
    private void sendToWxWork(String apiUrl, Map<String, Object> message) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, message, Map.class, getAccessToken());

        // 统一处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                throw new RuntimeException("发送失败: " + body.get("errmsg"));
            }
        } else {
            throw new RuntimeException("请求失败: " + response.getStatusCode());
        }
    }
}